package com.squirrel.common.shiro;

import com.squirrel.common.entity.User;
import com.squirrel.common.exception.MyAuthenticationException;
import com.squirrel.common.service.UserService;
import com.squirrel.common.response.code.CodeEnum;
import com.squirrel.common.util.Audience;
import com.squirrel.common.util.JwtTokenUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;

/**
 * @Description 自定义Realm
 * @Author 关远键
 * @Version v1.0.0
 * @Date 2021/11/8 10:19
 */
@Slf4j
public class UserRealm extends AuthorizingRealm {

    @Autowired
    private UserService userService;

    @Override
    public boolean supports(AuthenticationToken token) {
        return token instanceof JwtToken;
    }

    /**
     * 授权
     * @author 关远键
     * @date 2021/11/10 17:02
     * @param principals
     * @return org.apache.shiro.authz.AuthorizationInfo
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        System.out.println("执行了==>doGetAuthorizationInfo");

        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();

        Subject subject = SecurityUtils.getSubject();
        User currentUser = (User) subject.getPrincipal();

        log.info("最近的用户：" + currentUser.toString());

        info.addStringPermission("user:vip");
        return info;
    }

    /**
     * 认证
     * @author 关远键
     * @date 2021/11/9 21:42
     * @param token
     * @return org.apache.shiro.authc.AuthenticationInfo
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        System.out.println("执行了==>doGetAuthenticationInfo");

        String userToken = (String) token.getCredentials();
        log.info("userToken:" + userToken);

        Audience audience = Audience.getInstance();
        log.info("audience:" + audience);

        Integer userId = JwtTokenUtil.getUserId(userToken, audience.getBase64Secret());

        User user = userService.getUserById(userId);
        // 用户不存在
        if (null == user) {
            throw new MyAuthenticationException(CodeEnum.AUTHENTICATION_EXCEPTION);
        }

        // 加盐
//        return new SimpleAuthenticationInfo(user, user.getPassword(), ByteSource.Util.bytes(user.getNickname()), "");
        return new SimpleAuthenticationInfo(userToken, userToken, getName());
    }
}
